@echo off
rem Generate and build Visual Studio 2022 project (requires CMake and Visual Studio)
rem Usage: build_vs2022.bat [x64|x86] [Release|Debug]

setlocal

rem Script directory (with trailing backslash)
set SCRIPT_DIR=%~dp0

rem --- ensure SCRIPT_DIR does not end with a backslash to avoid quoting issues ---
if "%SCRIPT_DIR:~-1%"=="\" (
  set "SCRIPT_DIR=%SCRIPT_DIR:~0,-1%"
)

rem Default parameters
if "%1"=="" (
  set ARCH=x64
) else (
  set ARCH=%1
)
if "%2"=="" (
  set CFG=Release
) else (
  set CFG=%2
)

rem Map common alias to VS arch names
if /I "%ARCH%"=="x86" (
  set VS_ARCH=Win32
) else (
  set VS_ARCH=%ARCH%
)

rem Check cmake existence
where cmake >nul 2>&1
if errorlevel 1 (
  echo Error: CMake not found in PATH. Install CMake and ensure it is in PATH.
  exit /b 1
)

rem Ensure CMakeLists.txt exists in project root (SCRIPT_DIR)
if not exist "%SCRIPT_DIR%\CMakeLists.txt" (
  echo Error: CMakeLists.txt not found in project root "%SCRIPT_DIR%". Make sure the script is located in the project folder.
  exit /b 3
)

rem Prepare build directory (use absolute path)
set BUILD_DIR=%SCRIPT_DIR%\build_vs2022

if not exist "%BUILD_DIR%" mkdir "%BUILD_DIR%"

pushd "%BUILD_DIR%"

rem Configure with CMake (specify generator and architecture)
cmake -G "Visual Studio 17 2022" -A "%VS_ARCH%" -S "%SCRIPT_DIR%" -B "%BUILD_DIR%"
if errorlevel 1 (
  echo CMake configuration failed.
  popd
  exit /b 1
)

rem Build specified configuration (parallel)
cmake --build "%BUILD_DIR%" --config "%CFG%" --parallel
if errorlevel 1 (
  echo Build failed.
  popd
  exit /b 2
)

rem Success message
if exist "%BUILD_DIR%\simple_stack_demo.sln" (
  echo Build succeeded. Solution: "%BUILD_DIR%\simple_stack_demo.sln"
) else (
  echo Build succeeded. Check "%BUILD_DIR%" for output (e.g. %CFG% folder).
)

popd
endlocal
